package com.bbcare.followup.plat.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.DateUtil;
import com.bbcare.comm.ErrorCode;
import com.bbcare.comm.PropertiesUtils;
import com.bbcare.comm.ResultModel;
import com.bbcare.comm.ToolUtils;
import com.bbcare.department.plat.entity.DepartmentBasic;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.followup.plat.entity.FollowQueue;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IFollowQueueService;
import com.bbcare.followup.plat.service.IMabcEvaluationService;
import com.bbcare.followup.plat.service.IPatientFollowService;
import com.bbcare.followup.plat.service.IPatientService;

/**
 * 安医大MABC
 * @name:         MabcEvaluationController.java
 * @author:       tao
 * @createTime:   2018年3月9日
 * @description:  MabcEvaluationController.java
 * @modify:
 *
 */
@Controller
@RequestMapping("/webapi/service")
public class MabcEvaluationController {

    private final Log logger = LogFactory.getLog(MabcEvaluationController.class);

    @Autowired
    private IPatientService patientService;

    @Autowired
    private IMabcEvaluationService mabcEvaluationService;

    @Autowired
    private IFollowQueueService followQueueService ;

    @Autowired
    private IDepartmentBasicService deparmentBasicService;

    @Autowired
    private IFollowEvaluationService followEvaluationService;

    @Autowired
   	private IBsStaticParamService bsStaticParamService;

    @Autowired
   	private IPatientFollowService patientFollowService;

    //mabc检查用户不能为空
  	@RequestMapping("/mabc/checkUserInfo")
	@ResponseBody
	public ResultModel<Object> checkMabcUserInfo(@RequestBody String arg,HttpServletRequest request) throws Exception {
		logger.info("in checkMabcUserInfo----arg==" + arg);
	    JSONObject jsonEsb = JSON.parseObject(arg);
	    JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
	  	}

	    String hisNo = requestParam.getString("hisNo");
	    if (StringUtils.isEmpty(hisNo)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "儿童编码不能为空！"));
	    }
	    String phoneNo = requestParam.getString("phoneNo");
	    if (StringUtils.isEmpty(phoneNo)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "手机号不能为空！"));
	    }
	    String userName = requestParam.getString("userName");
	    if (StringUtils.isEmpty(userName)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "宝宝姓名不能为空！"));
	    }

	    String queueId = requestParam.getString("queueId");
	    if (StringUtils.isEmpty(queueId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列不能为空！"));
	    }

	    Map<String,Object> parma = new HashMap<String,Object>();
        parma.put("id",queueId);
        FollowQueue depObj = followQueueService.getQueueDetailByQueueId(parma);

		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"队列信息不存在");
		}

		DepartmentBasic dept = deparmentBasicService.getDepartmentBasicDetails(depObj.getDeptId());


		requestParam.put("tenantId",depObj.getTenantId());
		requestParam.put("hisNo1",hisNo);
	    Map<String,Object> retout = mabcEvaluationService.checkUserInfo(requestParam);
	    if(null != retout){
	    	retout.put("deptName", dept.getDeptName());
	    	retout.put("hospName", dept.getHospName());
	    	retout.put("deptId", dept.getId());
	    }
	    return new ResultModel<Object>(retout);
	}

  	//
  	@RequestMapping("/mabc/completeList")
	@ResponseBody
	public ResultModel<Object> getCompleteList(@RequestBody String arg,HttpServletRequest request) throws Exception {
		logger.info("in getCompleteList----arg==" + arg);
	    JSONObject jsonEsb = JSON.parseObject(arg);
	    JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
	  	}

	    String userId = requestParam.getString("userId");
	    if (StringUtils.isEmpty(userId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户id不能为空！"));
	    }
	    String queueId = requestParam.getString("queueId");
	    if (StringUtils.isEmpty(queueId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列不能为空！"));
	    }

	    Map<String,Object> parma = new HashMap<String,Object>();
        parma.put("id",queueId);
        FollowQueue depObj = followQueueService.getQueueDetailByQueueId(parma);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"队列信息不存在");
		}

		String tenantId =depObj.getTenantId();
		parma.clear();
		parma.put("tenantId",tenantId);
		parma.putAll(requestParam);
	    Map<String,Object> retout = mabcEvaluationService.getMabcCompleteList(parma);
	    return new ResultModel<Object>(retout);
	}

  	//mabc各种评估问卷获取
    @ResponseBody
    @RequestMapping("/mabc/getMabcQuestion")
    public ResultModel<Object> getMabcQuestion(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in getMabcQuestion----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String busiId = requestParam.getString("busiId");
        if(StringUtils.isEmpty(busiId)){
        	logger.info("out getMonthlyPostion----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"评估问卷编码不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("busiId",busiId);

		//年龄限制3岁以上  如果app用户自己修改时间 就不准
		List<JSONObject> list  = mabcEvaluationService.getMabcCommonPostion(paramsMap);
        /*if(Constants.MABC_BASIC_INFO.equals(busiId)){

		}else if(Constants.MABC_BABY.equals(busiId)){

		}else if(Constants.MABC_FAMILY.equals(busiId)){

		}else if(Constants.MABC_FATHER.equals(busiId)){

		}else if(Constants.MABC_MOTHER.equals(busiId)){

		}else if(Constants.MABC_FEED.equals(busiId)){

		}else if(Constants.MABC_EDUCATION.equals(busiId)){

		}else if(Constants.MABC_HEART.equals(busiId)){

		}else if(Constants.MABC_SCREEN.equals(busiId)){

		}else if(Constants.MABC_SLEEP.equals(busiId)){

		}else{
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"问卷类型传入有误");
		}*/
		return new ResultModel<Object>(list);
    }

    //mabc各种评估问卷提交
    @ResponseBody
    @RequestMapping("/mabc/questionSubmit")
    public ResultModel<Object> questionSubmit(@RequestBody String arg,
            HttpServletRequest request) throws Exception {
    	logger.info("in questionSubmit----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String busiId = requestParam.getString("busiId");
        if(StringUtils.isEmpty(busiId)){
        	logger.info("out questionSubmit----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"评估问卷编码不能为空");
        }

        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

		String queueId = requestParam.getString("queueId");
        if(StringUtils.isEmpty(queueId)){
        	logger.info("out questionSubmit----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"队列不能为空");
        }

        String postionIds = requestParam.getString("postionIds");
	    if (StringUtils.isEmpty(postionIds)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "答题内容不能为空！"));
	    }

        String userId = requestParam.getString("userId");
	    if (StringUtils.isEmpty(userId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户id不能为空！"));
	    }

		Map<String,Object> parma = new HashMap<String,Object>();
        parma.put("id",queueId);
        FollowQueue depObj = followQueueService.getQueueDetailByQueueId(parma);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"队列信息不存在");
		}

		String tenantId =depObj.getTenantId();
		parma.clear();

		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("busiId",busiId);
		paramsMap.put("tenantId",tenantId);
		paramsMap.put("userId",userId);
		paramsMap.put("postionIds",postionIds);

		Map<String,Object> rspMap  = mabcEvaluationService.mabcCommonSubmit(paramsMap);

		return new ResultModel<Object>(rspMap);
    }


    @RequestMapping("/mabc/scoredetail")
	@ResponseBody
	public ResultModel<Map<String, Object>> getMabcHistoryScoreDetail(@RequestBody String arg,
            HttpServletRequest request) throws Exception{
		logger.info("in getMabcHistoryScoreDetail----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        /*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
    	}

        String evaluationId = requestParam.getString("answerId");
        if(StringUtils.isEmpty(evaluationId)){
        	logger.info("out getMabcHistoryScoreDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，评测记录id不能为空");
        }

        String busiId ="";
        String tenantId ="";
        String gender ="";
		Map<String, Object> paramsMap = new HashMap<String, Object>();
		requestParam.put("evaluationId",evaluationId);
        Map<String, Object> resultMap= followEvaluationService.selectPtEvaluationResultDetail(requestParam);
        if(null != resultMap){
        	 String result = (String)resultMap.get("answerResult");
             String score =  (String)resultMap.get("result");

             tenantId  =  (String)resultMap.get("tenantId");
             busiId =  (String)resultMap.get("type");
			 gender =  (String)resultMap.get("gender");

             JSONObject obj =JSON.parseObject(score);
             if(null != obj){
             	paramsMap.putAll(obj);
             }
             paramsMap.put("postionIds",JSON.parseObject(result));
             paramsMap.put("busiId",busiId);

             String birthday = "";
     		 if(!StringUtils.isEmpty(resultMap.get("birthday"))){
     			 birthday =resultMap.get("birthday").toString();
     		 }

     	     String pregnancyDay = "";
     	     if(StringUtils.isEmpty(resultMap.get("pregnancyDay"))){
     	    	 pregnancyDay = "280";
     	     }else{
     	    	 pregnancyDay = resultMap.get("pregnancyDay").toString();
     	     }

             Long birthLong=ToolUtils.getCorrect(birthday,Integer.parseInt(pregnancyDay));//生日时间戳
      		 String age = ToolUtils.getCommAgeByBirthday(resultMap.get("testTime").toString(),DateUtil.getDate_8(new Date(birthLong)));
      		 paramsMap.put("age",age);
      		 long ageDay = (DateUtil.getDate_8(resultMap.get("testTime").toString()).getTime()-birthLong)/(1000*60*60*24);
             long ageMonth = (long) (ageDay/Constants.MONTH_DAY);
    		 paramsMap.put("age",age);
			 paramsMap.put("gender",gender);
    		 paramsMap.put("ageMonth",ageMonth+"月龄");

	         paramsMap.put("userName", resultMap.get("userName"));
	         paramsMap.put("userId", resultMap.get("userId"));
	 		 paramsMap.put("birthday",birthday);
	 		 paramsMap.put("pregnancyDay",pregnancyDay);
      		 paramsMap.put("testTime",resultMap.get("testTime").toString());
        }


        Map<String,Object> queryMap = new HashMap<String,Object>();
//		queryMap.put("type",Constants.ASSESSMENT_MABC_TYPE);
		queryMap.put("paramCode",busiId);
		List<Map<String,Object>> busiList = bsStaticParamService.getStaticParamsByCondition(queryMap);
		if(!CollectionUtils.isEmpty(busiList)){
	        paramsMap.put("evaluationName",busiList.get(0).get("paramName"));
		}

		Map<String, Object> mapIn = new HashMap<String, Object>();
        mapIn.put("tenantId", tenantId);
		Map<String, Object> deptMap = patientFollowService.getHospitalInfo(mapIn);
 		paramsMap.put("hospName",deptMap.get("hospitalName"));
 		paramsMap.put("deptName",deptMap.get("deptName"));

		logger.info("out getMabcHistoryScoreDetail----arg==" + paramsMap);
		return new ResultModel<Map<String,Object>>(paramsMap);
    }


    @RequestMapping("/mabc/getBasicInfo")
	@ResponseBody
	public ResultModel<Object> getMabcBasicInfo(@RequestBody String arg,
            HttpServletRequest request) throws Exception{
		logger.info("in getMabcBasicInfo----arg==" + arg);
        JSONObject jsonEsb = JSON.parseObject(arg);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "无data节点！");
		}

		String userId = requestParam.getString("userId");
	    if (StringUtils.isEmpty(userId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户id不能为空！"));
	    }

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.putAll(requestParam);
//        paramMap.put("examinationPaperName",type);

        String queueId = requestParam.getString("queueId");
	    if (StringUtils.isEmpty(queueId)) {
	        throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列不能为空！"));
	    }

	    Map<String,Object> parma = new HashMap<String,Object>();
        parma.put("id",queueId);
        FollowQueue depObj = followQueueService.getQueueDetailByQueueId(parma);

		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"队列信息不存在");
		}
		paramMap.put("tenantId", depObj.getTenantId());

        Map<String, Object> retMap = mabcEvaluationService.getMabcBasicInfo(paramMap);
		logger.info("out getMabcBasicInfo----arg==");
		return new ResultModel<Object>(retMap);
    }


	@RequestMapping("/mabc/appList")
	@ResponseBody
	public ResultModel<Object> getAppList(@RequestBody String arg,HttpServletRequest request) throws Exception {
		logger.info("in getCompleteList----arg==" + arg);
		JSONObject jsonEsb = JSON.parseObject(arg);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		/*channel渠道类型必传字段app登陆时特殊处理标识，跳过登陆*/
		String channel = requestParam.getString("channel");
		if(null == channel || !PropertiesUtils.getProperty("channel").equals(channel)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "channel传入为空或者传入值不正确!");
		}

		String userId = requestParam.getString("userId");
		if (StringUtils.isEmpty(userId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "用户id不能为空！"));
		}
		String queueId = requestParam.getString("queueId");
		if (StringUtils.isEmpty(queueId)) {
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "队列不能为空！"));
		}

		Map<String,Object> parma = new HashMap<String,Object>();
		parma.put("id",queueId);
		FollowQueue depObj = followQueueService.getQueueDetailByQueueId(parma);
		if(null == depObj){
			throw new AppException(ErrorCode.DEPARTMENT_EXCEPTION_TYPE_DEPARTMENT_NOT_EXIST,"队列信息不存在");
		}

		String tenantId =depObj.getTenantId();
		parma.clear();
		parma.put("tenantId",tenantId);
		parma.putAll(requestParam);
		List<Map<String, Object>> questionList = mabcEvaluationService.getMabcAppList(parma);
		return new ResultModel<Object>(questionList);
	}
}
